package org.example.MedicalCrowdsourcing.controller;

import org.example.MedicalCrowdsourcing.model.CommonResponse;
import org.example.MedicalCrowdsourcing.model.entity.BlockchainProject;
import org.example.MedicalCrowdsourcing.model.entity.BlockchainTransaction;
import org.example.MedicalCrowdsourcing.repository.BlockchainProjectRepository;
import org.example.MedicalCrowdsourcing.service.BlockchainSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 区块链数据控制器
 */
@RestController
@RequestMapping("/api/medical-crowdsourcing/blockchain")
public class BlockchainController {
    
    private static final Logger logger = LoggerFactory.getLogger(BlockchainController.class);
    
    @Autowired
    private BlockchainSyncService blockchainSyncService;
    
    @Autowired
    private BlockchainProjectRepository blockchainProjectRepository;
    
    /**
     * 获取项目的区块链交易记录
     */
    @GetMapping("/transactions/{projectId}")
    public ResponseEntity<Object> getProjectTransactions(@PathVariable BigInteger projectId) {
        List<BlockchainTransaction> transactions = blockchainSyncService.getProjectTransactions(projectId);
        
        List<Map<String, Object>> result = transactions.stream().map(tx -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", tx.getId());
            map.put("blockchainId", tx.getBlockchainId());
            map.put("transactionHash", tx.getTransactionHash());
            map.put("blockNumber", tx.getBlockNumber());
            map.put("status", tx.getStatus());
            map.put("createdAt", tx.getCreatedAt());
            map.put("creator", tx.getCreator() != null ? tx.getCreator().getUsername() : null);
            return map;
        }).collect(Collectors.toList());
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取交易记录成功", result);
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取交易详情
     */
    @GetMapping("/transactions/detail/{transactionHash}")
    public ResponseEntity<Object> getTransactionDetail(@PathVariable String transactionHash) {
        // 实际实现可以根据交易哈希从区块链获取详细信息
        // 这里简化为从数据库获取
        logger.info("获取交易详情: {}", transactionHash);
        
        Map<String, Object> result = new HashMap<>();
        result.put("transactionHash", transactionHash);
        result.put("status", "需要实现实际查询逻辑");
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取交易详情成功", result);
        return ResponseEntity.ok(response);
    }
    
    /**
     * 手动触发区块链数据同步
     */
    @PostMapping("/sync")
    public ResponseEntity<Object> syncBlockchainData() {
        logger.info("手动触发区块链数据同步");
        try {
            blockchainSyncService.checkAndResyncBlockchainData();
            CommonResponse response = new CommonResponse(CommonResponse.OK, "区块链数据同步已触发", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("区块链数据同步失败", e);
            CommonResponse response = new CommonResponse("500", "区块链数据同步失败: " + e.getMessage(), null);
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取区块链项目列表
     */
    @GetMapping("/projects")
    public ResponseEntity<Object> getBlockchainProjects() {
        List<BlockchainProject> projects = blockchainProjectRepository.findAll();
        
        List<Map<String, Object>> result = projects.stream().map(project -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", project.getId());
            map.put("blockchainId", project.getBlockchainId());
            map.put("title", project.getTitle());
            map.put("description", project.getDescription());
            map.put("status", project.getStatus());
            map.put("createdAt", project.getCreatedAt());
            map.put("creator", project.getCreator() != null ? project.getCreator().getUsername() : null);
            return map;
        }).collect(Collectors.toList());
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取区块链项目列表成功", result);
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取区块链项目详情
     */
    @GetMapping("/projects/{blockchainId}")
    public ResponseEntity<Object> getBlockchainProjectDetail(@PathVariable BigInteger blockchainId) {
        Optional<BlockchainProject> projectOpt = blockchainProjectRepository.findByBlockchainId(blockchainId);
        
        if (!projectOpt.isPresent()) {
            CommonResponse response = new CommonResponse("404", "区块链项目不存在", null);
            return ResponseEntity.ok(response);
        }
        
        BlockchainProject project = projectOpt.get();
        Map<String, Object> result = new HashMap<>();
        result.put("id", project.getId());
        result.put("blockchainId", project.getBlockchainId());
        result.put("title", project.getTitle());
        result.put("description", project.getDescription());
        result.put("status", project.getStatus());
        result.put("dataHash", project.getDataHash());
        result.put("blockchainHash", project.getBlockchainHash());
        result.put("createdAt", project.getCreatedAt());
        result.put("updatedAt", project.getUpdatedAt());
        result.put("completedAt", project.getCompletedAt());
        result.put("creator", project.getCreator() != null ? project.getCreator().getUsername() : null);
        
        // 获取相关交易
        List<BlockchainTransaction> transactions = blockchainSyncService.getProjectTransactions(blockchainId);
        List<Map<String, Object>> txList = transactions.stream().map(tx -> {
            Map<String, Object> map = new HashMap<>();
            map.put("transactionHash", tx.getTransactionHash());
            map.put("blockNumber", tx.getBlockNumber());
            map.put("createdAt", tx.getCreatedAt());
            return map;
        }).collect(Collectors.toList());
        
        result.put("transactions", txList);
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取区块链项目详情成功", result);
        return ResponseEntity.ok(response);
    }
} 